<template>
  <div class="debt-page">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" inline label-width="80px" class="search-bar">
      <el-form-item label="老人姓名">
        <el-input 
          v-model="searchForm.elderlyName" 
          placeholder="请输入" 
          clearable 
        />
      </el-form-item>
      <el-form-item label="床位号">
        <el-input 
          v-model="searchForm.bedNo" 
          placeholder="请输入" 
          clearable 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="default" @click="handleReset">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      border 
      stripe 
      :loading="loading" 
      style="width: 100%; margin-top: 16px;"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="elderlyName" label="老人姓名" min-width="120" />
      <el-table-column prop="bedNo" label="床位号" min-width="100" />
      <el-table-column 
        prop="debtAmount" 
        label="欠款金额（元）" 
        width="140" 
        align="right"
      />
      <el-table-column 
        prop="payDeadline" 
        label="支付截止时间" 
        width="180" 
        align="center"
      />
      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-button 
            type="text" 
            text-color="#409EFF" 
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-wrap">
      <div class="total-info">共 {{ total }} 项数据</div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="sizes, prev, pager, next, jumper"
        :total="total"
        background
      />
    </div>

    <!-- 欠费账单弹框（核心新增） -->
    <el-dialog
      title="查看欠费账单"
      v-model="dialogVisible"
      width="70%"
      :before-close="closeDialog"
      center
    >
      <!-- 加载状态 -->
      <div v-if="dialogLoading" class="dialog-loading">加载中...</div>
      
      <!-- 账单表格 -->
      <el-table 
        v-else
        :data="dialogBills" 
        border 
        style="width: 100%"
        empty-text="该老人暂无欠费账单"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="billNo" label="账单编号" />
        <el-table-column prop="billMonth" label="账单月份" />
        <el-table-column 
          prop="paymentDeadline" 
          label="支付截止时间" 
          width="180" 
          align="center"
        />
        <el-table-column 
          prop="payableAmount" 
          label="应付金额（元）" 
          width="140" 
          align="right"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElDialog, ElTable, ElTableColumn } from 'element-plus'
import request from '@/utils/request' // 项目封装的请求工具
import { useRouter } from 'vue-router'

const router = useRouter()

// 搜索表单
const searchForm = ref({
  elderlyName: '', // 老人姓名
  bedNo: ''        // 床位号
})

// 表格数据 & 分页
const tableData = ref([])
const total = ref(0)      // 总数据量
const pageSize = ref(6)  // 每页条数
const currentPage = ref(1)// 当前页码
const loading = ref(false)// 加载状态

// 弹框相关（核心新增）
const dialogVisible = ref(false)      // 弹框显示状态
const dialogBills = ref([])          // 弹框内的账单数据
const dialogLoading = ref(false)     // 弹框加载状态
const currentElderlyName = ref('')   // 当前查看的老人姓名

// 获取主列表数据（原有逻辑）
const getList = () => {
  loading.value = true
  request({
    url: '/system/bill/refundList', // 替换为实际接口地址
    method: 'get',
    params: {
      ...searchForm.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
  }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '数据获取失败')
    }
  }).catch(() => {
    ElMessage.error('网络异常，请重试')
  }).finally(() => {
    loading.value = false
  })
}

// 搜索事件（原有逻辑）
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置事件（原有逻辑）
const handleReset = () => {
  searchForm.value = { elderlyName: '', bedNo: '' }
  handleSearch()
}

// 查看事件：打开弹框 + 请求该老人的欠费账单（核心新增）
const handleView = (row) => {
  currentElderlyName.value = row.elderlyName // 记录老人姓名
  fetchElderlyBills(row.elderlyName)         // 请求账单数据
  dialogVisible.value = true                 // 打开弹框
}

// 请求老人的欠费账单（核心新增）
const fetchElderlyBills = (elderlyName) => {
  dialogLoading.value = true
  request({
    url: '/system/bill/elderlyBills', // 后端需实现该接口，按老人姓名查账单
    method: 'get',
    params: { elderlyName }
  }).then(res => {
    if (res.code === 200) {
      dialogBills.value = res.data // 填充弹框表格数据
    } else {
      ElMessage.error(res.msg || '获取账单失败')
    }
  }).catch(() => {
    ElMessage.error('网络异常，请重试')
  }).finally(() => {
    dialogLoading.value = false
  })
}

// 关闭弹框（核心新增）
const closeDialog = () => {
  dialogVisible.value = false
  dialogBills.value = [] // 清空数据，避免缓存
}

// 分页事件（原有逻辑）
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getList()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 初始化加载（原有逻辑）
onMounted(() => {
  getList()
})
</script>

<style scoped>
.debt-page {
  padding: 24px;
  background: #fff;
}

.search-bar {
  margin-bottom: 12px;
}

.pagination-wrap {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  color: #666;
  font-size: 14px;
}

/* 表格样式优化 */
.el-table {
  --el-table-header-text-color: #333;
  --el-table-row-hover-bg-color: #f8f9fa;
}

.el-table-column--align-right {
  text-align: right;
}

/* 弹框样式优化 */
.el-dialog__header {
  border-bottom: 1px solid #eee;
}
.el-dialog__body {
  padding: 20px;
}
.dialog-loading {
  text-align: center;
  padding: 50px 0;
  color: #999;
}
</style>